const NodeRSA = require('node-rsa');
let loading = "";
let time = "";
const os = require("os");
let electron = require('electron');
let md5 = require('md5');
let ipc = require('electron').ipcRenderer;
const remote = require('electron').remote;
let nodeMachineId = require('node-machine-id');


/**
 * 发送一条通知
 */



export function dataURLtoFile(base64, filename) {//将base64转换为文件，dataurl为base64字符串，filename为文件名（必须带后缀名，如.jpg,.png）
    let arr = base64.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type: mime});
}

export function sendNotification(title, body, time, icon) {
    let notification = new window.Notification(title, {
        // 通知的标题, 将在通知窗口的顶部显示
        title: title,
        // 通知的副标题, 显示在标题下面 macOS
        subtitle: time,
        icon: icon,
        // 通知的正文文本, 将显示在标题或副标题下面
        body: body,
        // false有声音，true没声音
        silent: false,
        // 通知的超时持续时间 'default' or 'never'
        timeoutType: 'default',
    })
    notification.onclick = function () {
        ipc.send("notification-click");
    }
    // notification.show();
}

export function quitApp() {
    ipc.send('window-close');
}

export function resolveSMSContent(content, extractRules) {
    for (let i = 0; i < extractRules.length; i++) {
        let extractRule = extractRules[i];
        let filter = eval(extractRule.filter);
        let exec;
        if (filter.test(content)) {
            let patternStr = eval(extractRule.regex)
            let mainContent;
            let title = extractRule.title;
            let groupNames = extractRule.groupNames.split(",");
            let values = [];
            patternStr = eval(patternStr)
            exec = patternStr.exec(content);
            for (let i = 0; i < groupNames.length; i++) {
                let groupName = groupNames[i].split("|")[0];
                let param = {
                    key: groupNames[i].split("|")[1],
                    text: exec.groups[groupName]
                }
                if (extractRule.title.startsWith("#P#") && extractRule.title.replace("#P#", "") === groupName) {
                    title = exec.groups[groupName];
                    continue;
                }
                if (groupNames[i].split("|")[0] === 'main') {
                    mainContent = param;
                    continue;
                }
                values.push(param)
            }
            let card = {
                title: title,
                mainContent: mainContent,
                content: content,
                param: values,
                copyMain: extractRule.copyMain,
                showContent: extractRule.showContent
            }

            if (card.copyMain) {
                writeContentToClipBoard(card.mainContent.text);
            }

            console.log(card);
            return card;
        }


    }

    return '';
}

export function getDeviceId() {
    return nodeMachineId.machineIdSync();
    // return os.platform() + '_' + '_' + os.userInfo().gid + '_' + os.userInfo().uid + '_' + os.userInfo().username
}

export function getBrand() {
    return os.platform();
}


/**
 * 解析短信内容
 */
export function decodeMessage(data) {
    let privateKey = getStorage("privateKey");
    const nodeRsa = new NodeRSA();
    nodeRsa.importKey(privateKey, 'pkcs8-private-pem');
    const decrypted = nodeRsa.decrypt(data, 'utf8');
    console.log(decrypted);
    return JSON.parse(decrypted);
}

export function setStorage(key, value) {
    localStorage.setItem(key, value);
}

export function getStorage(key) {
    return localStorage.getItem(key);
}

export function removeStorage(key) {
    localStorage.removeItem(key);
}

export function newKeyPair(context) {
    // hideLoading();
    // showLoading(context, "正在生成秘钥对...",20)
    let pair = generatorKeyPair();
    uploadClientPublicKey(pair.publicKey, pair.privateKey, context);
}


/**
 * 生成秘钥对
 * 公钥上传到服务器
 * 私钥保存在本地
 */
export function generatorKeyPair() {
    const key = new NodeRSA({b: 2048}); //生成2048位的密钥
    let publicDer = key.exportKey("pkcs8-public"); //公钥
    let privateDer = key.exportKey("pkcs8-private");//私钥
    console.log("公钥:", publicDer);
    console.log("私钥:", privateDer);
    return {
        publicKey: publicDer,
        privateKey: privateDer
    };
}

export function uploadClientPublicKey(publicKey, privateKey, context) {
    let reg = /\n/g;
    publicKey = publicKey.replace(reg, '');
    publicKey = publicKey.replace("-----BEGIN PUBLIC KEY-----", "").replace("-----END PUBLIC KEY-----", "");
    console.log(publicKey);
    let url = getHttpPath() + "/device/key"
    network(url, "POST", {'publicKey': publicKey}, function () {
        hideLoading();
        setStorage("privateKey", privateKey);
    }, function (event, data) {
        hideLoading();
    })


}


const clipboard = require('electron').clipboard

export function writeContentToClipBoard(content) {
    clipboard.writeText(content)
}

export function encodePassword(password) {
    return md5(password + "sync_tool" + password);
}

export function showLoading(context, text, timeout) {
    loading = context.$loading({
        lock: true,
        text: text,
        // spinner: 'el-icon-loading',
        background: 'rgba(255,255,255,0.75)'
    });
    if (typeof timeout == 'undefined') {
        timeout = 10 * 1000;
    } else {
        timeout = timeout * 1000;
    }
    time = setTimeout(() => {
        try {
            loading.close();
        } catch (e) {

        }
    }, timeout);
}


export function formatTime(timestamp) {
    let time = new Date(parseInt(timestamp));
    return time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds();

}

export function showMessage(context, type, text) {
    context.$message({
        message: text,
        type: type,
        center: true
    });
}


export function hideLoading() {
    clearTimeout(time)
    try {
        loading.close();
    } catch (e) {
    }
}

export function network(url, method, data, success, error) {
    data.deviceUid = getDeviceId();
    data.type = os.type();
    $.ajax({
        type: method,
        url: url,
        contentType: 'application/json',
        data: method !== "GET" ? JSON.stringify(data) : data,
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", getStorage("token"))
        },
        success: function (data) {
            success(data);
        },
        error: function (event, xhr, options, exc) {
            error(event, event.responseJSON);
        },
        dataType: 'json'
    })
}

export function globalData(name) {
    return remote.getGlobal(name);

}


export function getHttpPath() {
    let protocol = getStorage("protocol")
    if (protocol == null) {
        protocol = default_protocol;
    }
    let address = getStorage("address");
    if (address == null) {
        address = default_domain;
    }
    return protocol + address;
}

export function getWebSocketPath() {
    let protocol = getStorage("protocol");
    if (protocol == null) {
        protocol = default_protocol;
    }
    let address = getStorage("address");
    if (address == null) {
        address = default_domain;
    }
    protocol = protocol.replace("http", "ws");
    return protocol + address;
}




